<?php

class School
{
  public function load($id)
  {
    foreach(Db::fetchRow("SELECT * FROM schools WHERE school_id = $id") as $key=>$value)
    {
      $this->$key = $value;
    }
    return $this;
  }
  
  public function loadFromHash($hash)
  {
    $row = Db::fetchRow("SELECT * FROM schools WHERE school_hash = '$hash'");
    if(empty($row))
    {
      //BAD HASH, TRY TO AUTO-REPAIR?
      die("bad school_id");
    }
    foreach($row as $key=>$value)
    {
      $this->$key = $value;
    }
    return $this;
  }
  
  public function log($action)
  {
    Db::query("INSERT INTO logs(school_id, timestamp, action) VALUES (".$this->school_id.",".time().",'$action');");
  }
  
  public function createForm()
  {
    $form = new Form();
    foreach(Db::fetchAll("SELECT question_id FROM categories_questions WHERE category_id = " . $this->category_id) as $question_id)
    {
      $question = new Question();
      $question->load($question_id['question_id']);
      $form->addQuestion($question);
    }
    $form->setSchool($this);
    
    // SET OLD VALUES IF THEY WANT TO CHANGE IT
    $positive_answers = array();
    foreach(Db::fetchAll("SELECT * FROM schools_answers WHERE school_id = " . $this->school_id) as $row)
    {
      $positive_answers[$row['answer_id']] = $row['answer_specified'];
    }
    foreach($form->questions as $question)
    {
      foreach($question->answers as $answer)
      {
        if(!array_key_exists($answer->answer_id,$positive_answers))
        {
          $answer->setValue(false);
          continue;
        }
        if($answer->answer_need_specify)
        {
          $answer->setValue($positive_answers[$answer->answer_id]);
        }
        else
        {
          $answer->setValue(true);
        }
      }
    }
    
    return $form;
  }
  
}
